import store from '~/store'

const { state } = store

export class DictService {

  private static dictShortCode = (code: string) => {
    if (!code) return ""
    return code.slice(code.indexOf(".") + 1)
  }

  private static isType = (code: string, type: string) => {
    if (!type) return false
    return code.startsWith(type.concat("."))
  }

  /**
   * 获取字典数据
   * @param codes
   */
  static getDict(...codes) {
    let results: Array<string> = []

    // 获取字典项
    codes.forEach(code => {
      let items = state.dataDict
        .filter(x => DictService.isType(x.code, code))
        .map(x => ({
          code: DictService.dictShortCode(x.code),
          name: x.name,
          seq: x.seq
        }))
      results.push(...items)
    })
    return results.length === 1 ? results[0] : results
  }

  /**
   * 转换数据字典
   * @param type 
   * @param shortCode 
   */
  static dictConvert(type: string, shortCode: string) {
    const dict: any = state.dataDict
                           .find((x: any) => x.code === type.concat('.').concat(shortCode))
    if (!dict) {
      return ''
    }     
    return dict.name
  }
}
